import path from 'path'
import fs from 'fs'
import { fileURLToPath } from 'url'
import ora from 'ora'
import prompts from 'prompts'
import { delFile, isExist } from './utils/format.js'
import { red } from 'kolorist'

// 模板位置
const templateDir = path.resolve(fileURLToPath(import.meta.url), '..', '..', 'template/index.jsonc')

export default async (targetDir: string, targetPath: string) => {
  let result = {}
  try {
    result = await prompts([
      {
        type: () =>
          isExist(targetPath) ? 'confirm' : null, // 目标文件 如果存在并且为空
        name: 'overwrite',
        message: '配置文件已存在，是否重新生成？'
      }
    ],
    {
      onCancel: () => {
        throw new Error(red('✖') + ' 操作被取消')
      }
    })
  } catch (error) {
    console.log((error as Error).message)
    return
  }
  const { overwrite } = result as {overwrite: boolean}

  if (overwrite) { // 清空目标文件
    delFile(targetPath)
  } else if (overwrite === false) {
    console.log(red('✖') + ' 操作被取消')
    return
  }

  const spinner = ora('正在生成配置文件...').start()

  // 判断是否存在本地文件
  if (!fs.existsSync(targetDir)) {
    // 同步在本地创建目录
    fs.mkdirSync(targetDir, { recursive: true })
  }
  fs.copyFileSync(templateDir, targetPath)
  spinner.succeed('配置文件已生成')
}
